package com.iot.hmi.controller;

import com.iot.hmi.entity.*;
import com.iot.hmi.pojo.IotItemVO;
import com.iot.hmi.pojo.LatestValueVO;
import com.iot.hmi.protocol.AbstractProtocol;
import com.iot.hmi.protocol.ProtocolHandler;
import com.iot.hmi.service.HmiApiService;
import com.iot.hmi.service.HmiApiServiceImpl;
import com.iot.hmi.utils.SqliteHelper;
import com.iot.hmi.utils.TimeHelper;
import com.iot.hmi.view.SiemensWindowsView;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SiemensWindowsController extends SiemensWindowsView {

    private final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    @FXML
    private TableView<DataRow> dataTable;
    @FXML
    private TableColumn<DataRow, String> addressColumn;
    @FXML
    private TableColumn<DataRow, String> dataTypeColumn;
    @FXML
    private TableColumn<DataRow, String> readTypeColumn;
    @FXML
    private TableView<LatestValueVO> dataTable2;
    @FXML
    private TableColumn<LatestValueVO, String> itemAddressColumn;
    @FXML
    private TableColumn<LatestValueVO, Double> collectValueColumn;
    @FXML
    private TableColumn<LatestValueVO, String> collectStampColumn;
    @FXML
    private TableView<DailyDuration> newDataTable;
    @FXML
    private TableColumn<DailyDuration, String> dateColumn;
    @FXML
    private TableColumn<DailyDuration, Long> shutdownDurationColumn;
    @FXML
    private TableColumn<DailyDuration, Long> standbyDurationColumn;
    @FXML
    private TableColumn<DailyDuration, Long> loadDurationColumn;
    @FXML
    private TableView<WeeklyDuration> newDataTable2;
    @FXML
    private TableColumn<WeeklyDuration, String> weekColumn;
    @FXML
    private TableColumn<WeeklyDuration, Long> shutdownDurationColumn2;
    @FXML
    private TableColumn<WeeklyDuration, Long> standbyDurationColumn2;
    @FXML
    private TableColumn<WeeklyDuration, Long> loadDurationColumn2;
    @FXML
    private TextField shutdownTextField1;
    @FXML
    private TextField shutdownTextField2;
    @FXML
    private Label label1;
    @FXML
    private TextField standByTextField1;
    @FXML
    private TextField standByTextField2;
    @FXML
    private Label label2;
    @FXML
    private TextField loadTextField1;
    @FXML
    private TextField loadTextField2;
    @FXML
    private Label label3;

    private final ObservableList<DataRow> data = FXCollections.observableArrayList();
    private final HmiApiService hmiApiService = new HmiApiServiceImpl();
    private TimerTask autoRefreshTask;
    private Timer autoRefreshTimer;
    private IotDevice currentDevice;
    private IotDevice savedDevice; // 用于保存设备信息
    private ProtocolHandler currentProtocolHandler;
    private ObservableList<IotDeviceItem> iotDeviceItems = FXCollections.observableArrayList();
    private AbstractProtocol protocolService;
    private String deviceName;

    public static FXMLLoader getFxmlLoader() {
        URL url = SiemensWindowsController.class.getResource("/fxml/SiemensWindow.fxml");
        return new FXMLLoader(url);
    }

    private ObservableValue<String> createCollectStampCellValue(LatestValueVO latestValueVO) {
        if (latestValueVO == null) {
            return new SimpleStringProperty("");
        }
        return new SimpleStringProperty(TimeHelper.stamp2datetime(latestValueVO.getCollectStamp()));
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 左侧上方表格数据初始化
        // 设置地址列
        addressColumn.setCellValueFactory(cellData -> cellData.getValue().addressProperty());
        // 设置数据类型列
        dataTypeColumn.setCellValueFactory(cellData -> cellData.getValue().dataTypeProperty());
        dataTypeColumn.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<String>() {
            @Override
            public String toString(String object) {
                return object;
            }

            @Override
            public String fromString(String string) {
                return string;
            }
        }, FXCollections.observableArrayList("uint16", "int16", "uint32", "int32", "float32", "float64")));

        // 设置读取方式列
        readTypeColumn.setCellValueFactory(cellData -> cellData.getValue().readTypeProperty());
        readTypeColumn.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<String>() {
            @Override
            public String toString(String object) {
                return object;
            }

            @Override
            public String fromString(String string) {
                return string;
            }
        }, FXCollections.observableArrayList("ABCD", "BADC", "CDAB", "DCBA")));
        processAlgorithmComboBox.getItems().add("负载限值");
        processAlgorithmComboBox.setValue("负载限值");

        dataTable.setEditable(true);
        addressColumn.setEditable(true);
        dataTypeColumn.setEditable(true);
        readTypeColumn.setEditable(true);

        // 设置addressColumn可编辑
        addressColumn.setCellValueFactory(cellData -> cellData.getValue().addressProperty());
        addressColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        // 设置dataTypeColumn可编辑
        dataTypeColumn.setCellValueFactory(cellData -> cellData.getValue().dataTypeProperty());
        // 设置readTypeColumn可编辑
        readTypeColumn.setCellValueFactory(cellData -> cellData.getValue().readTypeProperty());
        // 绑定onEditCommit事件
        addressColumn.setOnEditCommit(this::handleEditCommit);
        dataTypeColumn.setOnEditCommit(this::handleEditCommit);
        readTypeColumn.setOnEditCommit(this::handleEditCommit);

        // 添加空行以允许用户开始编辑
        dataTable.setPlaceholder(new Label("双击或点击任意列开始新增"));
        dataTable.setRowFactory(tv -> {
            TableRow<DataRow> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (!row.isEmpty())) {
                    int index = row.getIndex();
                    TableColumn<DataRow, String> column = (TableColumn<DataRow, String>) dataTable.getColumns().get(0); // 根据需要选择列
                    dataTable.edit(index, column);
                }
            });
            return row;
        });

        dataTable.setItems(data);

        // 表格行点击事件
        dataTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                handleRowClick(newValue);
            }
        });
        // 左侧下方表格数据初始化
        itemAddressColumn.setCellValueFactory(cellData -> cellData.getValue() == null ? null : cellData.getValue().itemAddressProperty());
        collectValueColumn.setCellValueFactory(cellData -> cellData.getValue() == null ? null : cellData.getValue().collectValueProperty().asObject());
        collectStampColumn.setCellValueFactory(cellData -> createCollectStampCellValue(cellData.getValue()));
        // 初始化 newDataTable 列
        dateColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
        shutdownDurationColumn.setCellValueFactory(cellData -> cellData.getValue().shutdownDurationProperty().asObject());
        standbyDurationColumn.setCellValueFactory(cellData -> cellData.getValue().standbyDurationProperty().asObject());
        loadDurationColumn.setCellValueFactory(cellData -> cellData.getValue().loadDurationProperty().asObject());

        // 初始化 newDataTable2 列
        weekColumn.setCellValueFactory(cellData -> cellData.getValue().weekProperty());
        shutdownDurationColumn2.setCellValueFactory(cellData -> cellData.getValue().shutdownDurationProperty().asObject());
        standbyDurationColumn2.setCellValueFactory(cellData -> cellData.getValue().standbyDurationProperty().asObject());
        loadDurationColumn2.setCellValueFactory(cellData -> cellData.getValue().loadDurationProperty().asObject());
    }


    private void handleEditCommit(TableColumn.CellEditEvent<DataRow, String> event) {
        DataRow dataRow = event.getRowValue();
        String newValue = event.getNewValue();

        if (dataRow == null || newValue == null || newValue.trim().isEmpty()) {
            return;
        }

        switch (event.getTableColumn().getId()) {
            case "addressColumn":
                dataRow.setAddress(newValue);
                break;
            case "dataTypeColumn":
                dataRow.setDataType(newValue);
                break;
            case "readTypeColumn":
                dataRow.setReadType(newValue);
                break;
            case "valueColumn":
                dataRow.setValue(newValue);
                break;
        }

        System.out.println("Edited: " + event.getTableColumn().getText() + " to " + newValue);
        dataTable.refresh(); // 刷新表格显示

        // 如果是新增行，则添加到数据源
        if (dataRow.getAddress() != null && !dataRow.getAddress().trim().isEmpty()) {
            if (!data.contains(dataRow)) {
                data.add(dataRow);
            }
        }
    }

    @FXML
    private void addRowActionEvent() {
        data.add(new DataRow("", "", "", ""));
    }

    @FXML
    private void removeRowActionEvent() {
        ObservableList<DataRow> selectedRows = dataTable.getSelectionModel().getSelectedItems();
        data.removeAll(selectedRows);
    }

    @FXML
    private void showDeviceInputDialog() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/DeviceInputDialog.fxml"));
            AnchorPane dialogPane = loader.load();
            DeviceInputDialogController controller = loader.getController(); // 获取实际的控制器实例

            // 恢复之前保存的设备信息
            if (savedDevice != null) {
                controller.saveDevice(savedDevice);
            }

            Stage dialogStage = new Stage();
            dialogStage.setTitle("采集信息");
            dialogStage.setScene(new Scene(dialogPane));
            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                IotDevice device = controller.getDevice();
                // 处理设备信息，例如设置到当前设备
                currentDevice = device;
                savedDevice = device; // 保存设备信息
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @FXML
    private void showDeviceInfoDialog() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/DeviceInfoDialog.fxml"));
            DialogPane dialogPane = loader.load();
            DeviceInfoDialogController controller = loader.getController();

            // 创建Dialog对象
            Dialog<ButtonType> dialog = new Dialog<>();
            dialog.setDialogPane(dialogPane);
            dialog.setTitle("设备信息");

            // 将Dialog对象传递给控制器
            controller.setDialog(dialog);

            if (currentDevice != null) {
                DeviceInfo deviceInfo = SqliteHelper.queryDeviceInfo(currentDevice.getId());
                controller.setDeviceInfo(deviceInfo);
                controller.saveDeviceInfo(currentDevice.getId()); // 设置deviceId
                assert deviceInfo != null;
                deviceName = deviceInfo.getDeviceName();
            }

            // 显示对话框并等待用户操作
            dialog.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 连接按钮的点击事件
     */
    public void connectButtonActionEvent() {
        try {
            sendMsgToShow("");
            String address = currentDevice.getProtocolHost();
            int portInt = currentDevice.getProtocolPort();
            if (portInt <= 0 || portInt > 65535) {
                sendMsgToShow("端口号错误！");
                return;
            }
            if (address != null || !"".equals(address.trim())) {
                DeviceInfo deviceInfo = SqliteHelper.queryDeviceInfo(currentDevice.getId());
                assert deviceInfo != null;
                deviceName = deviceInfo.getDeviceName();
                // 获取模型下拉框选中的值
                protocolService = hmiApiService.protocolConnect(currentDevice);
                if (protocolService != null) {
                    System.out.println(protocolService.isConnected());
                    // 获取设备明细列表并展示在表格中
                    iotDeviceItems = FXCollections.observableArrayList(hmiApiService.listItems(address, portInt));
                    if (iotDeviceItems.isEmpty()) {
                        sendMsgToShow("请添加采集项点！");
                        return;
                    }
                    statusImg.setImage(new Image("/images/greenRound.png"));
                    sendMsgToShow(address + " 连接成功！");
                    currentProtocolHandler = hmiApiService.startShader(protocolService, iotDeviceItems, Integer.parseInt(String.valueOf(interval.getText())));
                    data.clear();
                    for (IotDeviceItem item : iotDeviceItems) {
                        data.add(new DataRow(item.getItemAddress(), item.getItemType(), item.getItemStyle(), ""));
                    }

                    // 获取最新数据并显示在 dataTable2 中
                    List<LatestValueVO> latestValues = hmiApiService.listLatestValue(address, portInt);
                    ObservableList<LatestValueVO> latestValuesObservableList = FXCollections.observableArrayList();
                    for (LatestValueVO latestValue : latestValues) {
                        latestValue.setCollectStamp(latestValue.getCollectStamp());
                        latestValuesObservableList.add(latestValue);
                    }
                    dataTable2.setItems(latestValuesObservableList);
//                    interval.setEditable(false);
                } else {
                    sendMsgToShow("连接失败！");
                }
            } else {
                sendMsgToShow(" Ip地址不能为空！");
            }
        } catch (Exception e) {
            sendMsgToShow("连接失败！");
        }
    }

    /**
     * 断开连接点击事件
     */
    public void disconnectionButtonActionEvent() {
        try {
            sendMsgToShow("");
            if (protocolService != null) {
                currentProtocolHandler.closeShader();
                protocolService.disConnect();
                statusImg.setImage(new Image("/images/redRound.png"));
                sendMsgToShow("断开连接！");
            }
        } catch (Exception e) {
            tipsLabel.setText(sdf.format(new Date()) + e.getMessage());
            e.printStackTrace();
        }
    }

    //保存按钮
    public void saveButtonActionEvent() {
        // 保存数据到数据库的代码
        List<IotDeviceItem> deviceItems = new ArrayList<>();
        for (DataRow row : data) {
            IotDeviceItem item = new IotDeviceItem();
            item.setItemAddress(row.getAddress());
            item.setItemType(row.getDataType());
            item.setItemStyle(row.getReadType());
            deviceItems.add(item);
        }
        try {
            hmiApiService.saveDeviceAndItems(currentDevice, deviceItems);
            sendMsgToShow("数据保存成功！");
        } catch (SQLException e) {
            sendMsgToShow("数据保存失败！");
            e.printStackTrace();
        }
    }

    private void handleRowClick(DataRow dataRow) {
        // 获取开始时间和结束时间
        LocalDateTime startTime = startDateTimePicker.getDateTime();
        LocalDateTime endTime = endDateTimePicker.getDateTime();

        // 格式化时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = startTime.format(formatter);
        String endTimeStr = endTime.format(formatter);

        // 获取图表数据
        try {
            List<IotItemValue> itemValues = hmiApiService.listValueByTimeRange(currentDevice.getProtocolHost(), currentDevice.getProtocolPort(), dataRow.getAddress(), startTimeStr, endTimeStr);

            // 绘制图表
            ObservableList<XYChart.Data<String, Number>> data = FXCollections.observableArrayList();
            for (IotItemValue value : itemValues) {
                long timestamp = value.getValueStamp();
                LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.of("+08:00"));
                String timeLabel = dateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                data.add(new XYChart.Data<>(timeLabel, value.getItemValue()));
            }

            XYChart.Series<String, Number> series = new XYChart.Series<>();
            if(deviceName!=null&& !deviceName.isEmpty()){
                series.setName(deviceName);
            }else {
                series.setName(currentDevice.getProtocolHost()+":"+currentDevice.getProtocolPort());
            }

            series.setData(data);

            dataLineChart.getData().clear();
            dataLineChart.getData().add(series);
            // 设置节点不显示
            for (XYChart.Data<String, Number> dataPoint : series.getData()) {
                dataPoint.getNode().setVisible(false);
            }
            series.getNode().setStyle("-fx-stroke-width: 1; -fx-stroke: blue;");

            // 拉取配置
            IotItemVO itemConfigAndProcess = hmiApiService.getItemConfig(currentDevice.getProtocolHost(), currentDevice.getProtocolPort(), dataRow.getAddress());

            // 设置 IotItemConfig 的数据
            IotItemConfig config;
            if (itemConfigAndProcess.getConfig() != null) {
                config = itemConfigAndProcess.getConfig();
                shutdownTextField1.setText(config.getShutMin().toString());
                shutdownTextField2.setText(config.getShutMax().toString());
                standByTextField1.setText(config.getWaitMin().toString());
                standByTextField2.setText(config.getWaitMax().toString());
                loadTextField1.setText(config.getLoadMin().toString());
                loadTextField2.setText(config.getLoadMax().toString());
            } else {
                config = null;
            }

            // 创建第二条线的数据系列
            XYChart.Series<String, Number> thresholdSeries = new XYChart.Series<>();
            thresholdSeries.setName("工艺状态");
            // 根据 processAlgorithmComboBox 的值设置第二条线的数据点
            if (config != null) {
                for (XYChart.Data<String, Number> dataPoint : series.getData()) {
                    String timeLabel = dataPoint.getXValue();
                    double seriesYValue = dataPoint.getYValue().doubleValue();
                    double thresholdYValue = 0.0;

                    switch (processAlgorithmComboBox.getValue()) {
                        case "负载限值":
                            if (seriesYValue >= config.getShutMin() && seriesYValue <= config.getShutMax()) {
                                thresholdYValue = config.getShutMin();
                            } else if (seriesYValue >= config.getWaitMin() && seriesYValue <= config.getWaitMax()) {
                                thresholdYValue = config.getWaitMin();
                            } else if (seriesYValue >= config.getLoadMin() && seriesYValue <= config.getLoadMax()) {
                                thresholdYValue = config.getLoadMax();
                            }
                            break;
                        // 其他算法的处理逻辑可以在这里添加
                        default:
                            thresholdYValue = seriesYValue; // 默认情况下，第二条线的Y值与第一条线相同
                            break;
                    }
                    thresholdSeries.getData().add(new XYChart.Data<>(timeLabel, thresholdYValue));
                }
            }

            // 设置节点颜色
            if (config != null) {
                // 初始化持续时间变量
                long[] shutdownDuration = {0};
                long[] standbyDuration = {0};
                long[] loadDuration = {0};

                // 遍历 series 中的数据点
                for (int i = 0; i < series.getData().size(); i++) {
                    XYChart.Data<String, Number> dataPoint = series.getData().get(i);
                    double seriesYValue = dataPoint.getYValue().doubleValue();

                    // 解析当前数据点的时间
                    LocalTime currentTime = LocalTime.parse(dataPoint.getXValue(), DateTimeFormatter.ofPattern("HH:mm:ss"));
                    // 假设今天是默认日期
                    LocalDate today = LocalDate.now();
                    LocalDateTime currentDateTime = LocalDateTime.of(today, currentTime);
                    long currentTimestamp = currentDateTime.toEpochSecond(ZoneOffset.of("+08:00"));

                    // 获取下一个数据点的时间戳（如果有）
                    long nextTimestamp = 0;
                    if (i < series.getData().size() - 1) {
                        LocalTime nextTime = LocalTime.parse(series.getData().get(i + 1).getXValue(), DateTimeFormatter.ofPattern("HH:mm:ss"));
                        LocalDateTime nextDateTime = LocalDateTime.of(today, nextTime);
                        nextTimestamp = nextDateTime.toEpochSecond(ZoneOffset.of("+08:00"));
                    } else {
                        // 如果是最后一个数据点，使用结束时间
                        nextTimestamp = endTime.toEpochSecond(ZoneOffset.of("+08:00"));
                    }

                    // 计算当前数据点的时间间隔
                    long duration = nextTimestamp - currentTimestamp;
                    if(duration < 0){
                        continue;
                    }
                    // 判断 seriesYValue 属于哪个区间，并累加相应的时间
                    if (seriesYValue >= config.getShutMin() && seriesYValue <= config.getShutMax()) {
                        shutdownDuration[0] += duration;
                    } else if (seriesYValue >= config.getWaitMin() && seriesYValue <= config.getWaitMax()) {
                        standbyDuration[0] += duration;
                    } else if (seriesYValue >= config.getLoadMin() && seriesYValue <= config.getLoadMax()) {
                        loadDuration[0] += duration;
                    }
                }

                // 将持续时间设置到对应的文本框中
                Platform.runLater(() -> {
                    label1.setText(String.format("%.1f 分钟", shutdownDuration[0] / 60.0));
                    label2.setText(String.format("%.1f 分钟", standbyDuration[0] / 60.0));
                    label3.setText(String.format("%.1f 分钟", loadDuration[0] / 60.0));
                });

                // 设置 thresholdSeries 的节点颜色
                for (XYChart.Data<String, Number> thresholdDataPoint : thresholdSeries.getData()) {
                    String timeLabel = thresholdDataPoint.getXValue();
                    double seriesYValue = series.getData().stream().filter(dataPoint -> dataPoint.getXValue().equals(timeLabel)).findFirst().map(dataPoint -> dataPoint.getYValue().doubleValue()).orElse(0.0);

                    // 使用 Platform.runLater 来设置节点样式
                    Platform.runLater(() -> {
                        if (thresholdDataPoint.getNode() != null) {
                            if (seriesYValue >= config.getShutMin() && seriesYValue <= config.getShutMax()) {
                                thresholdDataPoint.getNode().setStyle("-fx-background-color: red;");
                            } else if (seriesYValue >= config.getWaitMin() && seriesYValue <= config.getWaitMax()) {
                                thresholdDataPoint.getNode().setStyle("-fx-background-color: yellow;");
                            } else if (seriesYValue >= config.getLoadMin() && seriesYValue <= config.getLoadMax()) {
                                thresholdDataPoint.getNode().setStyle("-fx-background-color: green;");
                            }
                        }
                    });
                }
            }

            dataLineChart.getData().add(thresholdSeries);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    //刷新点击事件
    public void refreshButtonActionEvent() {
        // 获取最新数据并显示在 dataTable2 中
        try {
            if (currentDevice == null) {
                return;
            }
            List<LatestValueVO> latestValues = hmiApiService.listLatestValue(currentDevice.getProtocolHost(), currentDevice.getProtocolPort());
            ObservableList<LatestValueVO> latestValuesObservableList = FXCollections.observableArrayList(latestValues);
            dataTable2.setItems(latestValuesObservableList);

            // 使用当前选中的 DataRow 来更新图表数据
            DataRow selectedDataRow = dataTable.getSelectionModel().getSelectedItem();
            if (selectedDataRow != null) {
                handleRowClick(selectedDataRow);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void sendMsgToShow(String content) {
        tipsLabel.setText(sdf.format(new Date()) + " --> " + content);
    }

    //右侧文本框及表格保存按钮点击事件
    @FXML
    public void saveTextClickEvent() {
        // 获取当前选中的 DataRow
        DataRow selectedDataRow = dataTable.getSelectionModel().getSelectedItem();
        if (selectedDataRow == null) {
            sendMsgToShow("请选择一个设备明细行！");
            return;
        }
        String address = selectedDataRow.getAddress();
        // 获取 IotItemConfig 的数据
        IotItemConfig config = new IotItemConfig();
        config.setShutMin(Float.valueOf(shutdownTextField1.getText()));
        config.setShutMax(Float.valueOf(shutdownTextField2.getText()));
        config.setWaitMin(Float.valueOf(standByTextField1.getText()));
        config.setWaitMax(Float.valueOf(standByTextField2.getText()));
        config.setLoadMin(Float.valueOf(loadTextField1.getText()));
        config.setLoadMax(Float.valueOf(loadTextField2.getText()));

        try {
            hmiApiService.saveItemConfig(currentDevice.getProtocolHost(), currentDevice.getProtocolPort(), address, config);
            // 保存设备信息到弹框控制器
            DeviceInputDialogController.getInstance().saveDevice(currentDevice);
            sendMsgToShow("数据保存成功！");
        } catch (SQLException e) {
            sendMsgToShow("数据保存失败！");
            e.printStackTrace();
        }
    }

    //autoRefreshEvent
    @FXML
    public void autoRefreshEvent() {
        if (autoRefreshCheckBox.isSelected()) {
            // 开启自动刷新
            autoRefreshTimer = new Timer();
            autoRefreshTask = new TimerTask() {
                @Override
                public void run() {
                    Platform.runLater(() -> refreshButtonActionEvent());
                }
            };
            autoRefreshTimer.scheduleAtFixedRate(autoRefreshTask, 0, Integer.parseInt(String.valueOf(interval.getText())) * 1000L); // 根据interval的值设置刷新间隔
        } else {
            // 关闭自动刷新
            if (autoRefreshTask != null) {
                autoRefreshTask.cancel();
                autoRefreshTask = null;
            }
            if (autoRefreshTimer != null) {
                autoRefreshTimer.cancel();
                autoRefreshTimer = null;
            }
        }
    }

    public class DataRow {
        private final SimpleStringProperty address = new SimpleStringProperty();
        private final SimpleStringProperty dataType = new SimpleStringProperty();
        private final SimpleStringProperty readType = new SimpleStringProperty();
        private final SimpleStringProperty value = new SimpleStringProperty();

        public DataRow(String address, String dataType, String readType, String value) {
            setAddress(address);
            setDataType(dataType);
            setReadType(readType);
            setValue(value);
        }

        public String getAddress() {
            return address.get();
        }

        public void setAddress(String address) {
            this.address.set(address);
        }

        public StringProperty addressProperty() {
            return address;
        }

        public String getDataType() {
            return dataType.get();
        }

        public void setDataType(String dataType) {
            this.dataType.set(dataType);
        }

        public StringProperty dataTypeProperty() {
            return dataType;
        }

        public String getReadType() {
            return readType.get();
        }

        public void setReadType(String readType) {
            this.readType.set(readType);
        }

        public StringProperty readTypeProperty() {
            return readType;
        }

        public String getValue() {
            return value.get();
        }

        public void setValue(String value) {
            this.value.set(value);
        }

        public StringProperty valueProperty() {
            return value;
        }
    }
}
